const Op = require('sequelize').Op;
const Joi = require('@hapi/joi');
const Schema = require('../../schema/content.schema')
const Model = require('../../models/content.model')
const Category = require('../../models/category.model')
const Sequelize = require('sequelize');
module.exports = [
  {
    path: '',
    method: 'GET',
    handler: (request, h) => {
      // console.log(request.query)
      const page = request.query.page || 1;
      const sort = request.query.sort || 'publish_time';
      const desc = request.query.descending || false;
      const page_size = request.query.page_size || 20;
      const trashed = request.query.trashed || false;
      const category = request.query.category || null
      const search = request.query.search ? JSON.parse(request.query.search) : {}
      // const condition = {}
      return Model.findAndCountAll({
        offset: (page - 1) * page_size,
        limit: parseInt(page_size),
        order: [['top', 'asc'],[sort, desc ? 'desc' : 'asc']],
        where: {
          deletedAt: trashed ? { [Op.not]: null} : {[Op.is]: null},
          category: category ? category : { [Op.not]: null},
          title: search.title ? { [Op.like]:  '%' + search.title + '%' } : { [Op.not]: null} 
        },
        paranoid: !trashed,
        include: [
          { model: Category, as: 'categoryinfo' }
        ]
      }).then((result) => {
        return {
          total: result.count,
          per_page: 20,
          current_page: page,
          last_page: Math.ceil(result.count / 20),
          data: result.rows
        };
      }).catch((err) => {
        // request.log('debug', err);
        return h.response(err.message).code(500);
      });
    },
    options: {
      auth: false,
      tags: ['api', 'Content/Content'],
      description: '获取内容列表',
      notes: '根据查询条件获取内容列表',
      validate: {
        query: Joi.object({
          page: Joi.number().integer().positive().min(1).default(1).description('分页页码'),
          sort: Joi.string().default('publish_time').description('排序字段'),
          descending: Joi.boolean().default(true).description('是否desc'),
          page_size: Joi.number().integer().min(-1).default(20).description('分页容量'),
          trashed: Joi.boolean().default(false).description('是否显示已删除内容'),
          search: Joi.string().description('其他搜索条件'),
          category: Joi.number().integer().description('分类id')
        }).label('SearchCondition')
      },
      response: {
        schema: Joi.object({
          total: Joi.number().min(0),
          per_page: Joi.number().default(20),
          current_page: Joi.number().min(1),
          last_page: Joi.number().min(0),
          data: Joi.array().items(Schema.Default)
      }).label('ContentList')
      }
    }
  },
  {
    method: 'GET',
    path: '/{id}',
    handler: (request, h) => {
      Model.increment('hits', { where: { id: request.params[Model.pk] }});
      return Model.findByPk(request.params[Model.pk]).then((content) => {
        return content ? content : h.response('未找到！').code(500);
      });
    },
    options: {
      auth: false,
      tags: ['api', 'Content/Content'],
      description: '获取内容详情',
      notes: '根据ID获取内容列表',
      validate: {
        params: Joi.object({
          id: Joi.number().integer().positive().required().description('主键(id)')
        })
      },
      response: {
        schema: Schema.Default
      }
    }
  },
  {
    method: 'POST',
    path: '',
    handler: (request, h) => {
      return Model.create(request.payload).then((content) => {
          return '添加成功！';
      }).catch((err) => {
          request.log('debug', err);
          return h.response(err.message).code(500);
      });
    },
    options: {
      tags: ['api', 'Content/Content'],
      description: '新增内容',
      notes: '提交新增内容信息',
      validate: {
        // failAction: (request, h, err) => {
        //   console.log(err)
        //   console.log(err.details[0].path)
        //   console.log(err.output.payload.validation)
        //   console.log(Schema.Base)
        //   return err
        // },
        payload: Schema.Create
      },
      response: {
        schema: Joi.string().example('新增成功！')
      }
    }
  },
  {
    method: 'DELETE',
    path: '/{ids}',
    handler: (request, h) => {
      const ids = request.params.ids.split('_')
      return Model.destroy({
        where: {
          [Model.pk]: { [Op.in]: ids}
        }
      }).then((res) => {
        if (res === ids.length) {
            return '删除成功！';
        } else {
          return h.response('删除失败！找不到相关记录或id数目不匹配').code(500);
        }
      }).catch((err) => {
        request.log('debug', err);
        return h.response(err.message).code(500);
      });
    },
    options: {
      tags: ['api', 'Content/Content'],
      description: '删除内容',
      notes: '根据ID获取内容列表',
      validate: {
        params: Joi.object({
          ids: Joi.string().required().description('主键(id)')
        })
      },
      response: {
        schema: Joi.string().example('删除成功！')
      }
    }
  },
  {
    method: 'PUT',
    path: '/{id}',
    handler: (request, h) => {
      return Model.update(request.payload, {
        where: {
          [Model.pk]: request.params[Model.pk]
        }
      }).then((res) => {
        if (res[0] === 1) {
          return '更新成功！';
        }
        return '更新失败！';
      }).catch((err) => {
        request.log('debug', err);
        return h.response(err.message).code(500);
      });
    },
    options: {
      tags: ['api', 'Content/Content'],
      description: '更新内容',
      notes: '根据id更新内容信息',
      validate: {
        payload: Schema.Update
      },
      response: {
        schema: Joi.string().example('更新成功！')
      }
    }
  },
  {
    method: 'PUT',
    path: '/restore/{id}',
    handler: (request, h) => {
      return Model.restore({
        where: {
          'id': request.params[Model.pk]
        }
      }).then(() => {
        return '恢复成功！'
      }).catch((err) => {
        request.log('debug', err);
        return h.response(err.message).code(500);
      });
    },
    options: {
      tags: ['api', 'Content/Content'],
      description: '恢复已删除内容',
      notes: '根据id恢复已删除内容信息',
      validate: {
        params: Joi.object({
          id: Joi.number().integer().positive().required().description('主键(id)')
        })
      },
      response: {
        schema: Joi.string().example('恢复成功！')
      }
    }
  },
  {
    path: '/statistics',
    method: 'GET',
    handler: (request, h) => {
      return Model.findAll({
        attributes: [
          'category',
          [Sequelize.fn('COUNT', Sequelize.col('*')), 'count'],
          Sequelize.col('categoryinfo.name')
        ],
        group: 'category',
        // raw: true,
        include: [
          {
            model: Category,
            as: 'categoryinfo'
          }
        ]
      }).then(res => {
        return res
      })
    },
    options: {
      auth: false,
      tags: ['api', 'Content/Content'],
      description: '统计数据',
      notes: '获取统计数据',
      response: {
        schema: Joi.array()
      }
    }
  },
  {
    path: '/status_count',
    method: 'GET',
    handler: (request, h) => {
      return Model.findAll({
        attributes: ['status', ['count(*)', 'count']],
        group: 'status',
        raw: true
      }).then(res => {
        let st = {}
        res.forEach(e => {
          st[e['status']] = e['count']
        })
        return st
      })
    },
    options: {
      // auth: false,
      tags: ['api', 'Content/Content'],
      description: '状态统计数据',
      notes: '获取状态统计数据',
      response: {
        schema: Joi.object().description('状态统计数据！')
      }
    }
  },
  {
    path: '/export',
    method: 'GET',
    handler: (request, h) => {
      return 'export'
    },
    options: {
      tags: ['api', 'Content/Content'],
      description: '数据导出',
      notes: '获取导出数据文件',
      validate: {
        // params: Joi.object({
        //   id: Joi.number().integer().positive().required().description('主键(id)')
        // })
      },
      response: {
        schema: Joi.string().example('导出成功！')
      }
    }
  }
]